<template>
  <div>
    <el-input v-model="searchUsername" placeholder="请输入用户名" />
    <el-input v-model="searchEmail" placeholder="请输入邮箱" />
    <el-button @click="getUserList">查询</el-button>
    <el-button @click="openEditUI(null)" type="primary" icon="el-icon-plus" circle></el-button>

    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="id" label="用户ID" width="120" />
      <el-table-column prop="username" label="用户名" width="180" />
      <el-table-column prop="email" label="邮箱" width="240" />
      <el-table-column prop="phone" label="手机号" width="240" />
      <el-table-column prop="status" label="状态" width="120" />
      <el-table-column label="头像" width="120">
        <template slot-scope="scope">
          <img :src="scope.row.avatar" alt="Avatar" style="width: 50px; height: 50px; border-radius: 50%;" />
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status == '1' ? 'success' : 'danger'" disable-transitions>{{ scope.row.status == 1 ?
            '启用' : '禁用' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column>
        <template slot-scope="scope">
          <el-button @click="openEditUI(scope.row.id)" type="primary" icon="el-icon-edit" circle size="mini"></el-button>
          <el-button @click="deleteRole(scope.row)" type="danger" icon="el-icon-delete" circle size="mini"></el-button>
          <el-button @click="goBack()" type="primary">返回</el-button>
        </template>
      </el-table-column>
    </el-table>


    <!-- 分页-->
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
      :current-page="searchModel.pageNo" :page-sizes="[3, 6, 9, 12]" :page-size="searchModel.pageSize"
      layout="total, sizes, prev, pager, next, jumper" :total="total">
    </el-pagination>

    <!-- 对话框 -->
    <el-dialog @close="clearForm" :title="title" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
      <el-form :model="user" ref="roleFormRef" :rules="rules">
        <el-form-item prop="username" label="用户名称" :label-width="formLabelWidth">
          <el-input v-model="user.username" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item prop="email" label="用户邮箱" :label-width="formLabelWidth">
          <el-input v-model="user.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" :label-width="formLabelWidth">
          <el-input v-model="user.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="phone" label="用户手机号" :label-width="formLabelWidth">
          <el-input v-model="user.phone" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item  label="用户角色·" :label-width="formLabelWidth">
          <el-checkbox-group style="width: 85%;" v-model="user.roleIdList" :max="2">
          <el-checkbox v-for="(item) in roleList" :label="item.roleIdle" :key="item.roleId">
            {{item.roleDesc}}
          </el-checkbox>
           </el-checkbox-group>
          </el-form-item>
        <!-- </el-form-item>
        <el-checkbox v-model="selectAllRoles" @change="handleSelectAll">全选</el-checkbox>
        <el-form-item label="用户角色·" :label-width="formLabelWidth">
          <el-checkbox-group style="width: 85%;" v-model="user.roleIdList" :max="2">
            <el-checkbox v-for="(item) in roleList" :label="item.roleDesc" :key="item.roleId" :value="item.roleId">
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveUser()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { page } from '@/api/user'
import { deleteRoleById } from '@/api/user'
import { updateuser } from '@/api/user'
import { adduser } from '@/api/user'
import { queryById } from '@/api/user'
import roleManage from '@/api/roleManage'
export default {

  data() {
    return {
      selectAllRoles: false,
      roleList: [],
      formLabelWidth: '130px',
      title: '',
      tableData: [],
      total: 0,
      searchModel: {
        pageNo: 1,
        pageSize: 6,
      },
      searchUsername: '',
      searchEmail: '',
      user: {
        roleIdList: []
      },

      dialogFormVisible: false,
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 10, message: '长度在 6 到 10 个字符', trigger: 'blur' }
        ]
      }

    };
  },
  mounted() {
    this.getUserList();
    this.getAllRole()
  },
  methods: {
    handleSelectAll(value) {
    if (value) {
      this.user.roleIdList = this.roleList.map(item => item.roleId);
    } else {
      this.user.roleIdList = [];
    }
  },
    getAllRole() {
      roleManage.getAllRole().then(response => {
        console.log(response.data)
        this.roleList = response.data
      });
    },
    handleSizeChange(val) {
      this.searchModel.pageSize = val
      this.getUserList()
    },
    handleCurrentChange(val) {
      this.searchModel.pageNo = val
      this.getUserList()
    },


    clearForm() {
      this.user = {
        roleIdList: []
      } // 清空 userForm 对象
      this.$refs.roleFormRef.clearValidate() // 清除表单验证状态

    },
    saveUser() {
      this.$refs.roleFormRef.validate((valid) => {
        if (valid) {
          if (this.user.id == null) {
            adduser(this.user).then(response => {
              // 添加成功后的操作
              this.dialogFormVisible = false; // 关闭编辑对话框
              this.clearForm(); // 清空表单数据
              this.getUserList(); // 刷新用户列表数据
            });
          } else {
            updateuser(this.user).then(response => {
              // 更新成功后的操作
              this.dialogFormVisible = false; // 关闭编辑对话框
              this.clearForm(); // 清空表单数据
              this.getUserList(); // 刷新用户列表数据
            });
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    openEditUI(id) {
      if (id == null) {
        this.title = '新增';
      } else {
        this.title = '修改';
        queryById(id).then(response => {
          this.user = response.data;
        });
      }
      this.dialogFormVisible = true;
    },



    goBack() {
      this.searchUsername = ''; // 清空用户名搜索条件
      this.searchEmail = ''; // 清空邮箱搜索条件
      // 返回操作逻辑
      this.getUserList();

    },
    deleteRole(role) {
      this.$confirm(`您确定删除角色 ${role.username} ？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'danger'
      }).then(() => {
        deleteRoleById(role.id).then(response => { // 调用删除角色的 API 方法
          this.$message({
            type: 'success',
            message: response.message
          });
          this.getUserList(); // 删除成功后刷新角色列表
        });

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    getUserList() {
      const username = this.searchUsername; // 查询条件：用户名
      const email = this.searchEmail; // 查询条件：邮箱

      page(this.searchModel.pageNo, this.searchModel.pageSize, username, email)
        .then(response => {

          this.tableData = response.data.records.filter(user => user.status !== '0' && user.deleted !== 1);
          this.searchModel.pageNo = response.data.current
          this.searchModel.pageSize = response.data.size
          this.total = response.data.total
          // this.roleList = response.data.records.roleIdList
        })
        .catch(error => {
          console.log(error);
        });
    }

  }
};
</script>

